package com.atguigu.cloud.controller;

import com.atguigu.cloud.entities.PayDTO;
import com.atguigu.cloud.resp.ResultData;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpMethod;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import java.net.URI;
import java.util.List;

/**
 * @author bairimengchang
 * @version 1.0
 * @project cloud2024
 * @description 核心控制器
 * @date 2024/9/12
 */
@RestController
@Slf4j
public class OrderController{
    public static final String PaymentSrv_URL = "http://cloud-payment-service";

    @Resource
    private RestTemplate restTemplate;

    @Resource
    private DiscoveryClient discoveryClient;

    // 新增订单
    // 这里原本是GetMapping
    @PostMapping("/consumer/pay/add")
    public ResultData addOrder(PayDTO payDTO){
        return restTemplate.postForObject(PaymentSrv_URL + "/pay/add", payDTO, ResultData.class);
    }

    // 按照ID查流水
    @GetMapping("/consumer/pay/get/{id}")
    public ResultData getPayInfo(@PathVariable("id") Integer id){
        return restTemplate.getForObject(PaymentSrv_URL + "/pay/get/"+id, ResultData.class, id);
    }

    // 查询所有流水
    @GetMapping("/consumer/pay/getAll")
    public ResultData getAll(){
        log.info("查询所有支付流水");
        return restTemplate.getForObject(PaymentSrv_URL + "/pay/getAll", ResultData.class);
    }

    // 按照ID删除流水
    @DeleteMapping("/consumer/pay/del/{id}")
    public ResultData deletePay(@PathVariable("id") Integer id){
        return restTemplate.exchange(
                PaymentSrv_URL + "/pay/del/"+id,
                HttpMethod.DELETE,
                null,
                ResultData.class
        ).getBody();
    }

    // 修改支付流水
    @PutMapping("/consumer/pay/update")
    public ResultData updatePay(PayDTO payDTO){
        HttpEntity<PayDTO> payDTOHttpEntity = new HttpEntity<>(payDTO);
        return restTemplate.exchange(
                PaymentSrv_URL + "/pay/update",
                HttpMethod.PUT,
                payDTOHttpEntity,
                ResultData.class
        ).getBody();
    }

    @Value("${server.port}")
    private String port;

    @GetMapping(value = "/pay/get/info")
    private String getInfoByConsul(@Value("${cleft.info}") String cleftInfo) {
        return "cleftInfo: "+cleftInfo+"\t"+"port: "+port;
    }

    @GetMapping(value = "/consumer/pay/get/info")
    private String getInfoByConsul() {
        return restTemplate.getForObject(PaymentSrv_URL + "/pay/get/info", String.class);
    }

    /*
    负载均衡算法：rest接口第几次请求数 % 服务器集群总数量 = 实际调用服务器位置下标  ，每次服务重启动后rest接口计数从1开始。
    当总请求数位3时： 3 % 2 =1 对应下标位置为1 ，则获得服务地址为127.0.0.1:8001
    当总请求数位4时： 4 % 2 =0 对应下标位置为0 ，则获得服务地址为127.0.0.1:8002
     */
    @GetMapping("/consumer/discovery")
    public String discovery() {
        // 获取所有服务的id
        List<String> services = discoveryClient.getServices();
        for (String element : services) {
            System.out.println("element: "+element);
        }

        System.out.println("===================================");

        // 根据服务id（这里写死为cloud-payment-service）获取服务实例信息
        List<ServiceInstance> instances = discoveryClient.getInstances("cloud-payment-service");
        for (ServiceInstance element : instances) {
            System.out.println(element);
            System.out.println(element.getUri());
        }

        return instances.get(0).getServiceId()+":"+instances.get(0).getPort();
    }

}